#include "stm32f10x.h"  
#include "Serial.h"
#include "OLED.h"
#include "Delay.h"
#include <string.h>

int ESP8266_strctn(char *str,char * needle) {
	char *p;
	char *np;
	int found = 0;
	while(*str != 0) {
		if(*str == *needle) {
			found = 1;
			p = str;
			np = needle;
			while(*np != 0) {
				if(*p != *np) {
					found = 0;
					break;
				}
				p++;
				np++;
			}
			if(found)
				return found;
		}
		str++;
	}
	return found;
}

void ESP8266_Init(void) {
	Serial_Init();
}

int ESP8266_WaitFor(char* forWhar,int timeout) {
	int i;
	u8* sstr;
	while(1) {
		if(timeout > 0 )timeout--;
		if(timeout == 0) {
			return 0;
		}
		if(!Serial_GetRxFlag())
			continue;
		sstr = Serial_GetRxString();
		for(i=0;i<Serial_GetDataPointer();i++) {
			if(sstr[i] == 0) {
				sstr[i] = '_';
			}
		}
		
		printf("\n(%d)%d[%s\n]\n",Serial_GetDataPointer(),strlen((char*)sstr),(char*)sstr);
		if(ESP8266_strctn((char*)sstr,forWhar)) {
			printf(">>>>>>>\n");
			Serial_ClearRxString();
			return 1;
		}
		if(Serial_GetOvFlag()) {
			Serial_ClearRxString();
		}
	}
}

int ESP8266_SendCmdAndWaitOK(char *cmd) {
	Serial_SendString(cmd);
	return ESP8266_WaitFor("OK",1000000);
}

int pass = 00;

void ESP8266_StartServer(void) {
	OLED_ShowString(1,1,"Starting Server");
	OLED_ShowString(2,1,"Prog:[");
	OLED_ShowChar(2,13,']');
	ESP8266_SendCmdAndWaitOK("AT\r\n") && (pass |= 0x20 >> 0);
	OLED_ShowBinNum(2,7,pass,6);
	ESP8266_SendCmdAndWaitOK("AT+CWMODE=1\r\n") && (pass |= 0x20 >> 1);
	OLED_ShowBinNum(2,7,pass,6);;
	Serial_SendString("AT+RST\r\n");
	ESP8266_WaitFor("OK",-1)  && (pass |= 0x20 >> 2);
	Delay_s(2);
	OLED_ShowBinNum(2,7,pass,6);
	Serial_SendString("AT+CWJAP=\"410\",\"12335678@410\"\r\n");
	ESP8266_WaitFor("GOT IP",-1);
	ESP8266_WaitFor("OK",-1)  && (pass |= 0x20 >> 3);
	OLED_ShowBinNum(2,7,pass,6);
	ESP8266_SendCmdAndWaitOK("AT+CIPMUX=1\r\n") && (pass |= 0x20 >> 4);
	OLED_ShowBinNum(2,7,pass,6);
	ESP8266_SendCmdAndWaitOK("AT+CIPSERVER=1,80\r\n")  && (pass |= 0x20 >> 5);
	OLED_ShowBinNum(2,7,pass,6);
	if(pass == 0x3f) {
		OLED_ShowString(1,1,"Server Running ");
	}
}
